package com.yl.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class TsToMp3Utils {

    public static void main(String[] args) {
        // 输入的TS文件列表
        String[] tsFiles = {
                "F:\\sw\\1.ts",
                "F:\\sw\\2.ts"
        };

        // 拼接TS文件
        concatenateTsFiles(tsFiles, "F:\\sw\\output.ts");

        // 转换TS到MP3
        convertTsToMp3("output.ts", "F:\\sw\\output.mp3");
    }

    private static void concatenateTsFiles(String[] tsFiles, String outputFile) {
        StringBuilder concatCommand = new StringBuilder("copy");
        for (String tsFile : tsFiles) {
            concatCommand.append(" + ");
            concatCommand.append(tsFile);
        }
        concatCommand.append(" ");
        concatCommand.append(outputFile);

        runFfmpegCommand(concatCommand.toString());
    }

    private static void convertTsToMp3(String inputFile, String outputFile) {
        String ffmpegCommand = String.format("ffmpeg -i %s -acodec libmp3lame -q:a 4 %s", inputFile, outputFile);
        runFfmpegCommand(ffmpegCommand);
    }

    private static void runFfmpegCommand(String command) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder();
            processBuilder.command("bash", "-c", command);
            Process process = processBuilder.start();

            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String line;
            while ((line = errorReader.readLine()) != null) {
                System.out.println(line);
            }

            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
